package DFS;

/**
 * @Classname 岛屿的周长463
 * @Description TODO
 * @Date 2023/3/15 21:35
 * @Created by xjl
 */
public class 岛屿的周长463 {

    int[][] dist=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};

    public int islandPerimeter(int[][] grid) {
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                if (grid[r][c] == 1) {
                    // 题目限制只有一个岛屿，计算一个即可
                    return dfs(grid, r, c);
                }
            }
        }
        return 0;
    }

    int dfs(int[][] grid, int i, int j) {
        // 函数因为「坐标 (r, c) 超出网格范围」返回，对应一条黄色的边
        if (i<0||i>=grid.length||j<0||j>=grid[0].length){
            return 1;
        }
        // 函数因为「当前格子是海洋格子」返回，对应一条蓝色的边
        if (grid[i][j] == 0) {
            return 1;
        }
        // 函数因为「当前格子是已遍历的陆地格子」返回，和周长没关系
        if (grid[i][j] != 1) {
            return 0;
        }
        grid[i][j] = 2;
        int count=0;
        for (int k=0;k<4;k++){
            int x=i+dist[k][0];
            int y=j+dist[k][1];
            count+=dfs(grid,x,y);
        }
        return count;
    }
}
